import _ from "lodash"

const imageSize = (url, callback) => {
  const image = new Image()
  image.src = `src/assets/images/${url}`
  image.onload = () => {
    callback(image.width, image.height)
  }
}

const imageSizeAsync = (url) => {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.src = `src/assets/images/${url}`
    image.onload = () => {
      resolve({
        name: url,
        width: image.width,
        height: image.height
      })
    }
  })
}

const imagesSizeAsync = (pics) => {
  return Promise.all(pics.map(pic => imageSizeAsync(pic)))
}

const minValIdx = (arr) => {
  return arr.indexOf(_.min(arr))
}

/**
 * 图片列表按列数分组
 * @param originPics 图片列表
 * @param size 分组数量
 * @param maxWidth
 * @param gap
 * */
const group = async (originPics, size, maxWidth, gap) => {
  const pics = await imagesSizeAsync(originPics)
  const matrix = new Array(size).fill(0).map(_ => [])
  const len = size
  const picLen = pics.length
  const height = new Array(size).fill(0)
  for (let idx = 0; idx < picLen; idx++) {
    const pic = pics[idx]
    const scale = maxWidth / pic['width']
    const minIdx = minValIdx(height)
    const y = height[minIdx] + (matrix[minIdx].length  * gap)
    const x = minIdx * maxWidth + minIdx * gap
    height[minIdx] = height[minIdx] + scale * pic.height
    matrix[minIdx].push({
      ...pic,
      x,
      y
    })
  }
  return matrix
}


const groupTest = (pics, size, maxWidth, gap) => {
  const matrix = new Array(size).fill(0).map(_ => [])
  const len = size
  const picLen = pics.length
  const height = new Array(size).fill(0)
  for (let idx = 0; idx < picLen; idx++) {
    const pic = pics[idx]
    const scale = maxWidth / pic['width']
    const minIdx = minValIdx(height)
    const y = height[minIdx] + (matrix[minIdx].length  * gap)
    const x = minIdx * maxWidth + minIdx * gap
    height[minIdx] = height[minIdx] + scale * pic.height
    matrix[minIdx].push({
      idx,
      ...pic,
      x,
      y
    })
  }
  return matrix
}


export {group, groupTest}
